//
//  ConfirmReturnCarViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/7/2.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit
import AMapSearchKit
import AipOcrSdk
import TBox
import CoreBluetooth

class ConfirmReturnCarViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AMapSearchDelegate {
    
    var order: Order.Detail?
    
    private var parkingPos: String = "1"
    
    private var tbox: TBox?
    
    var photoTime: Int?
    
    @IBOutlet weak var pos1: UIButton!
    @IBOutlet weak var pos2: UIButton!
    @IBOutlet weak var pos3: UIButton!
    
    @IBOutlet weak var remarkField: UITextField!
    @IBOutlet weak var parkingAddressField: UITextField!
    
    @IBOutlet weak var lightButton: UIButton!
    @IBOutlet weak var accButton: UIButton!
    @IBOutlet weak var gearButton: UIButton!
    @IBOutlet weak var doorButton: UIButton!
    
    var location: CLLocation?
    
    let search = AMapSearchAPI()
    
//    var carPlateNumber: String?
    
    var centralManager: CBCentralManager?
    var bluetoothState: CBManagerState = .unknown
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.global())
        
        search?.delegate = self
        
        if let location = location {
            let coordinate = location.coordinate
            let request = AMapReGeocodeSearchRequest()
            request.location = AMapGeoPoint.location(withLatitude: CGFloat(coordinate.latitude), longitude: CGFloat(coordinate.longitude))
            request.requireExtension = true
            search?.aMapReGoecodeSearch(request)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // MARK: - AMapSearchDelegate
    func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {
        if response.regeocode == nil {
            return
        }
        
        if let address = response.regeocode.formattedAddress {
            parkingAddressField.text = address
        }
    }
    
    // MARK: - IBAction
    
    @IBAction func confirmReturnCar(_ sender: UIButton) {
        let now = Int(Date().timeIntervalSince1970)
        
        //大于5分钟后退
        if order?.orderType == 2, let time = photoTime, now - time > 300 {
            self.navigationController?.popViewController(animated: true)
        }
        
        guard let orderId = order?.orderId else {
            showError("订单id错误")
            return
        }
        
        guard let loc = self.userLocation else {
            showError("抱歉，定位失败。请您确认当前位置(1038)")
            return
        }
        
        guard let address = self.parkingAddressField.text else {
            showError("请填写地址")
            return
        }
        
        guard address.count > 0 else {
            showError("请填写地址")
            return
        }
        
        var remarkString: String? = nil
        
        if parkingPos == "2" || parkingPos == "3" {
            guard let remark = remarkField.text else {
                showError("请填写备注")
                return
            }
            
            guard remark.count > 0 else {
                showError("请填写备注")
                return
            }
            
            remarkString = remark
        } else {
            remarkString = remarkField.text
        }
        
        guard bluetoothState == .poweredOn else {
            alert(message: "蓝牙连接失败，请您确认蓝牙已开启，如开启请靠近车辆在重新尝试(1040)")
            return
        }
        
        func confirmReturnCar(_ bluetoothType: Int) {
            JZLoading.showLoadingWith(toView: self.view, type: .special)
            Order.confirmReturnCar(orderId: orderId,
                                   parkingAddress: address,
                                   parkingPos: parkingPos,
                                   remark: remarkString,
                                   location: loc,
                                   bluetoothType: bluetoothType,
                                   success: { [weak self] car in
                                    JZLoading.hideLoading()
                                    if self?.order?.orderType == 1 {
                                        self?.performSegue(withIdentifier: "returnDetailSegue", sender: nil)
                                    } else if self?.order?.orderType == 2 {
                                        self?.performSegue(withIdentifier: "dayReturnDetailSegue", sender: nil)
                                    }
            }) { [weak self] error, car in
                JZLoading.hideLoading()
                if error.code == 1011 {
                    self?.accButton.setImage(UIImage(named: car?.accStatus == 1 ? "pull_key" : "un_pull_key"), for: .normal)
                    self?.doorButton.setImage(UIImage(named: car?.doorStatus == 1 ? "close_door" : "un_close_door"), for: .normal)
                    self?.lightButton.setImage(UIImage(named: car?.lightStatus == 1 ? "close_light" : "un_close_light"), for: .normal)
                    self?.gearButton.setImage(UIImage(named: car?.gearStatus == 1 ? "take_thing" : "un_take_thing"), for: .normal)
                } else {
                    if error.code == 1014 {
                        self?.alert(message: error.msg)
                    } else if error.code == 1015 {
                        self?.alertWithCancelButton(title: nil, message: error.msg, okTitle: "联系客服", cancelTitle: "稍后重试", okStyle: .default, completion: {
                            if let url = kCallCenter {
                                UIApplication.shared.open(url, options: [:], completionHandler: nil)
                            }
                        })
                    } else if error.code == 1017 || error.code == 1018 {
                        self?.alert(message: error.msg)
                    } else {
                        self?.showError(error)
                    }
                }
            }
        }
        
        if let name = order?.bluetoothName, let sn = order?.bluetoothSn, let code = order?.tboxDeviceCode {
            if let type = TBoxType(rawValue: code) {
                JZLoading.showLoadingWith(toView: self.view)
                tbox = TBox(type: type, name: name, password: sn)
                if let t = tbox {
                    t.auth(success: {
                        t.disconnect()
                        JZLoading.hideLoading()
                        confirmReturnCar(1)
                    }) { message in
                        t.disconnect()
                        JZLoading.hideLoading()
                        confirmReturnCar(2)
                    }
                }
            } else {
                confirmReturnCar(2)
            }
        } else {
            confirmReturnCar(2)
        }
    }
    
    @IBAction func selectParkingPos(_ sender: UIButton) {
        if sender == pos1 {
            parkingPos = "1"
            pos1.setImage(UIImage(named: "select"), for: .normal)
            pos2.setImage(UIImage(named: "unSelect"), for: .normal)
            pos3.setImage(UIImage(named: "unSelect"), for: .normal)
        } else if sender == pos2 {
            parkingPos = "2"
            pos1.setImage(UIImage(named: "unSelect"), for: .normal)
            pos2.setImage(UIImage(named: "select"), for: .normal)
            pos3.setImage(UIImage(named: "unSelect"), for: .normal)
        } else if sender == pos3 {
            parkingPos = "3"
            pos1.setImage(UIImage(named: "unSelect"), for: .normal)
            pos2.setImage(UIImage(named: "unSelect"), for: .normal)
            pos3.setImage(UIImage(named: "select"), for: .normal)
        }
    }
    
    @IBAction func closeBanner(_ sender: UIButton) {
        tableView.tableHeaderView = nil
    }
    
    // MARK: - Navigation
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "returnDetailSegue" {
            if let vc = segue.destination as? ReturnDetailViewController {
                vc.orderId = order?.orderId
            }
        } else if segue.identifier == "webViewSegue" {  //web
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController {
                vc.page = Page.server(.legend)
            }
        } else if segue.identifier == "dayReturnDetailSegue" {
            if let vc = segue.destination as? DayReturnDetailViewController {
                vc.orderId = order?.orderId
            }
        }
    }
}

// MARK: - Text Field Delegate

extension ConfirmReturnCarViewController: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        guard let text = textField.text else {
            return true
        }
        
        if range.length == 1 && string.count == 0 {
            return true
        } else if text.count >= 20 {
            textField.text = String(text.prefix(20))
            return false
        }
        
        return true
    }
}

extension ConfirmReturnCarViewController: CBCentralManagerDelegate {
    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        DispatchQueue.main.async { [weak self] in
            self?.bluetoothState = central.state
        }
    }
}
